﻿using System;
using UnityEngine;

namespace HotUpdate.Misc
{
    public static class UITool
    {
        /// <summary>
        /// 把child设置为parent的子节点，并且保持child的transform标准化
        /// </summary>
        /// <param name="child"></param>
        /// <param name="parent"></param>
        public static void SetTransformParent(Transform child, Transform parent)
        {
            child.SetParent(parent, false);
            child.localPosition = Vector3.zero;
            child.localScale = Vector3.one;
            child.localRotation = Quaternion.identity;
        }
        
        /// <summary>
        /// 递归寻找当前父节点下指定名字的子节点
        /// </summary>
        /// <param name="parent">父节点</param>
        /// <param name="name">子节点名称</param>
        /// <returns>找到的子节点RectTransform</returns>
        /// <exception cref="ArgumentException">当parent或name为空时抛出异常</exception>
        public static Transform RecursionFindObj(Transform parent, string name)
        {
            if (parent == null || string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("parent or name is null");
            }

            // 检查当前节点是否匹配目标名字
            if (parent.name.Equals(name))
            {
                return parent;
            }

            // 递归遍历每个子节点
            for (int i = 0; i < parent.childCount; i++)
            {
                Transform child = parent.GetChild(i) as Transform;
                if (child.name.Equals(name))
                {
                    return child;
                }

                if (child != null)
                {
                    Transform result = RecursionFindObj(child, name);
                    if (result != null)
                    {
                        return result;
                    }
                }
            }

            return null;
        }
    }
}